/**
 * This file is Copyright © 2008 Software Craftsmen Limited. All Rights Reserved.
 */
package com.softwarecraftsmen.cachecontrol.keys;

import org.jetbrains.annotations.NotNull;

import java.io.StringWriter;
import java.util.Arrays;

public class CompositeKey<V> extends AbstractKey<V>
{
	@NotNull
	private final Object[] orderedKeyComponents;

	public CompositeKey(@NotNull final Object... keys)
	{
		super();
		if (keys.length == 0)
		{
			throw new IllegalArgumentException("Can not be passed an empty varags of keys");
		}
		else if (keys.length == 1)
		{
			throw new IllegalArgumentException("Use a SimpleKey if creating keys of a length of one as it is more efficient");
		}
		this.orderedKeyComponents = keys;
	}

	public @NotNull String toString()
	{
		final StringWriter writer = new StringWriter();
		writer.write("CompositeKey(");
		for (int index = 0; index < orderedKeyComponents.length; index++)
		{
			writer.write(orderedKeyComponents[index].toString());
			if (index < orderedKeyComponents.length - 1)
			{
				writer.write(", ");
			}
		}
		writer.write(")");
		return writer.toString();
	}

	public int hash()
	{
		return Arrays.hashCode(orderedKeyComponents);
	}

	public boolean exactlyMatches(@NotNull final Key<V> key)
	{
		if (this == key)
		{
			return true;
		}
		if (!getClass().equals(key.getClass()))
		{
			return false;
		}

		final CompositeKey that = (CompositeKey) key;
		return Arrays.equals(orderedKeyComponents, that.orderedKeyComponents);
	}
}
